﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Abrs
{
    public partial class Upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += new EventHandler(Button1_Click);
        }

        void Button1_Click(object sender, EventArgs e)
        {
            byte[] byteArray = null;
            var name = "";
            if(FileUpload1.HasFile)
            {
                name = FileUpload1.FileName;
                var stream = FileUpload1.FileContent;
                stream.Seek(0, SeekOrigin.Begin);
                byteArray = new byte[stream.Length];
                int count = 0;
                while (count<stream.Length)
                {
                    byteArray[count++] = Convert.ToByte(stream.ReadByte());
                }

            }

            var exentdInex =
            name.LastIndexOf(".");
            var newName = name.Remove(exentdInex, 1).Insert(exentdInex, "_");

            var baseAddrees = "http://localhost:5252/Services/Rest/UploadFileService.svc/FileUpload/";
            var request = (HttpWebRequest) HttpWebRequest.Create(baseAddrees + newName);

            request.Method = "POST";
            request.ContentType = "text/plain";
            Stream serverStream = request.GetRequestStream();
            serverStream.Write(byteArray, 0, byteArray.Length);
            serverStream.Close();

            //var resp = (HttpWebResponse)request.GetResponse();
            //using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            //{
            //    int statusCode = (int)response.StatusCode;
            //    StreamReader reader = new StreamReader(response.GetResponseStream());

            //}
        }
    }
}